<?php
declare (strict_types=1);

namespace app\common\logic;

use app\common\model\DepartmentModel;
use app\common\validate\DepartmentValidate;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use utils\PHPTree;

/**=========================================
 * Copyright © 2023-2024, WICMS.CN. All Rights Reserved
 * Project Name: WiCMS
 * Description: 部门逻辑处理
 * Author: jason
 * Email: 52527998@QQ.COM
 * Date: 2024/12/15
 * Time: 00:08
 * File: app\common\Logic\Department.php
 * =========================================
 */
class DepartmentLogic extends BaseLogic
{

    public function _initialize(): void
    {
        parent::_initialize();
    }

    /**
     * @param array $condition
     * @param array $field
     * @param bool  $is_tree
     *
     * @return array|string
     */
    public static function getList(array $condition = [], array $field = [], bool $is_tree = false): array|string
    {
        $list = DepartmentModel::getList($condition, $field);
        if (empty($list)) return [];
        if ($is_tree) {
            return PHPTree::makeTree($list);
        }
        return $list;
    }


    /**
     * @param array $data
     *
     * @return bool|string
     */
    public static function saveData(array $data): bool|string
    {
        $id    = $data['id'] ?? 0;
        $scene = empty($id) ? 'add' : 'edit';
        unset($data['id']);
        try {
            validate(DepartmentValidate::class)
                ->scene($scene)
                ->check($data);
            if ($scene == 'add') {
                $department    = DepartmentModel::create($data);
                $department_id = $department->id;
            } else {
                DepartmentModel::update($data, ['id' => $id]);
                $department_id = $id;
            }
            // 修改当前部门结构树
            $parent_id = $data['pid'] ?? 0;
            if ($parent_id == 0) {
                $tree = '0,' . $department_id;
            } else {
                $tree = DepartmentModel::where('id', $parent_id)->value('department_tree');
            }
            DepartmentModel::update(['department_tree' => $tree . ',' . $department_id], ['id' => $department_id]);
            return true;
        } catch (ValidateException $e) {
            return $e->getError();
        }
    }

    /**
     * 删除部门
     *
     * @param int $id
     *
     * @return bool|string
     */
    public static function deleteData(int $id = 0): bool|string
    {
        if (empty($id)) return '参数错误';
        // 删除所有子级部门
        $findInSet = "FIND_IN_SET({$id},`department_tree`)";
        $model     = new DepartmentModel();
        $model->destroy($id, true);
        $model->whereRaw($findInSet)->delete();
        return true;
    }

    /**
     * 获取子级部门ID
     *
     * @param int $department_id
     *
     * @return array
     */
    public static function getDepartmentChildIds(int $department_id):array
    {
        return DepartmentModel::whereRaw("FIND_IN_SET({$department_id},`department_tree`)")->column('id');
    }

}